package com.delu.config;

import com.delu.entity.Advertisement;
import com.delu.mapper.AdvMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

public class RedisExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private AdvMapper advMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public RedisExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();

        Advertisement advertisement = advMapper.selectById(Long.parseLong(expiredKey));

        advertisement.setAdvStatus(0);

        redisTemplate.opsForZSet().remove("advShow", advertisement.getAdvId());

        System.out.println(expiredKey);
    }
}
